<template>
  <div class="container">
    <a-card class="general-card" title="查询表格">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="title" label="题目标题">
                  <a-input
                    v-model="formModel.title"
                    placeholder="请输入题目标题"
                  />
                </a-form-item>
              </a-col>
              <!-- 题目难度 -->
              <a-col :span="8">
                <a-form-item field="difficulty" label="题目难度">
                  <a-select
                    v-model="formModel.difficulty"
                    :options="difficultyTypeOptions"
                    placeholder="全部"
                  />
                </a-form-item>
              </a-col>
              <!-- 会员专属 -->
              <a-col :span="8">
                <a-form-item field="vip" label="专属VIP">
                  <a-select
                    v-model="formModel.vip"
                    :options="vipTypeOptions"
                    placeholder="全部"
                  />
                </a-form-item>
              </a-col>
              <!-- 所属题库 -->
              <a-col :span="8">
                <a-form-item field="questionBank" label="所属题库">
                  <a-select
                    v-model="formModel.questionBank"
                    :options="questionBankOptions"
                    placeholder="全部"
                  />
                </a-form-item>
              </a-col>
              <!-- 是否发布 -->
              <a-col :span="8">
                <a-form-item field="publish" label="是否发布">
                  <a-select
                    v-model="formModel.publish"
                    :options="publishOptions"
                    placeholder="全部"
                  />
                </a-form-item>
              </a-col>
              <!-- 自定义的标签选择器 -->
              <a-col :span="8">
                <a-form-item field="title" label="题目标签">
                  <a-auto-complete
                    v-model="formModel.tag"
                    :data="allTags"
                    :style="{ width: '360px' }"
                    placeholder="请输入题目标签"
                    @select="onSelect"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              查询
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button type="primary">
              <template #icon>
                <icon-plus />
              </template>
              新建
            </a-button>
          </a-space>
        </a-col>
        <a-col
          :span="12"
          style="display: flex; align-items: center; justify-content: end"
        >
          <a-tooltip content="刷新">
            <div class="action-icon" @click="search">
              <icon-refresh size="18" />
            </div>
          </a-tooltip>
        </a-col>
      </a-row>

      <!--      表格-->
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :columns="columns"
        :data="renderData"
        :stripe="true"
        :bordered="false"
        @page-change="onPageChange"
      >
        <!--        题目标题-->
        <template #questionTitle="{ record }">
          <!-- 当标题长度大于10时使用tooltip -->
          <a-tooltip
            v-if="record.title.length > 10"
            :content="record.title"
            background-color="#3491FA"
          >
            <span>{{ record.title.substring(0, 10) + '...' }}</span>
          </a-tooltip>
          <!-- 否则直接显示标题 -->
          <span v-else>{{ record.title }}</span>
        </template>

        <!--题目内容-->
        <template #questionContent="{ record }">
          <span>{{
            record.content.length > 10
              ? record.content.substring(0, 10) + '...'
              : record.content
          }}</span>

          <!--          题目难度-->
        </template>
        <template #questionDifficulty="{ record }">
          <a-tag v-if="record.difficulty === 0" color="pinkpurple">简单</a-tag>
          <a-tag v-else-if="record.difficulty === 1" color="magenta"
            >中等
          </a-tag>
          <a-tag v-else color="gray">困难</a-tag>
        </template>

        <!--        题目标签-->
        <template #questionTags="{ record }">
          <a-space>
            <a-tag
              v-for="(tag, index) in record.tags"
              :key="tag"
              :color="getTagColor(index)"
            >
              {{ tag }}
            </a-tag>
          </a-space>
        </template>

        <!--        时间-->
        <template #createdTime="{ record }">
          <span>{{ new Date(record.createdTime).toLocaleDateString() }}</span>
        </template>

        <!--        状态是否发布-->
        <template #status="{ record }">
          <a-space size="large">
            <a-switch
              :default-checked="record.status === 1"
              :disabled="false"
              @change="(checked) => changeStatus(record, checked as boolean)"
            >
              <template #checked>发布</template>
              <template #unchecked> 未发布</template>
            </a-switch>
          </a-space>
        </template>

        <!--        操作-->
        <template #operations="{ record }">
          <a-space>
            <!--            查看-->
            <a-button type="primary" status="success" @click="view(record)"
              >查看
            </a-button>
            <!--            修改-->
            <a-button type="primary" status="warning" @click="edit(record)"
              >修改
            </a-button>

            <a-button
              type="primary"
              status="danger"
              danger
              @click="deleteRecord(record)"
              >删除
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>
    <!--    Modal -->
    {{ showVisible }}
    <a-modal
      v-model:visible="showVisible"
      width="700px"
      :ok-text="showStatus === 1 ? '确认' : '保存'"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <template #title> 题目信息</template>
      <question-view
        v-show="showStatus === 1"
        :key="currentRecord"
        :data="currentRecord"
      ></question-view>
      <question-update
        v-show="showStatus === 2"
        :key="currentRecord"
        ref="formTable"
        :data="currentRecord"
      ></question-update>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import useLoading from '@/hooks/loading';
  import QuestionView from '@/views/list/components/question-view.vue';
  import QuestionUpdate from '@/views/list/components/question-update.vue';

  const renderData = ref([]);
  // 题库所属下拉框
  const questionBankOptions = ref([]);
  const currentRecord = ref();
  const showStatus = ref(0);
  // 子组件
  const formTable = ref();
  const pagination = reactive({
    current: 1,
    pageSize: 20,
  });
  const showVisible = ref(false);
  const allTags = [
    'JAVA',
    'C++',
    'C#',
    'JavaScript',
    'JQuery',
    'Python',
    'PHP',
  ]; // 所有的标签数据
  // 搜索项
  const formModel = reactive({
    title: '',
    difficulty: '',
    vip: '',
    questionBank: '',
    status: '',
    publish: '',
    tag: '',
  });
  const columns = [
    {
      title: '题目标题', // 列标题
      dataIndex: 'title',
      slotName: 'questionTitle',
    },
    {
      title: '题目内容',
      dataIndex: 'content',
      slotName: 'questionContent',
    },
    {
      title: '题目难度',
      dataIndex: 'difficulty',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      slotName: 'questionDifficulty',
    },
    {
      title: '标签',
      dataIndex: 'tags',
      slotName: 'questionTags',
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      slotName: 'createdTime',
    },
    {
      title: '状态',
      dataIndex: 'status',
      slotName: 'status',
    },
    {
      title: '操作',
      dataIndex: 'operations',
      slotName: 'operations',
    },
  ];

  const { loading, setLoading } = useLoading(true);
  const fetchData = async () => {
    setLoading(true); // 开始加载
    try {
      setTimeout(() => {
        // 模拟异步请求，设置2条数据
        const mockData = [
          {
            content: '37837',
            title: '呜呜呜呜呜呜呜飞法沙发沙发打赏洒发',
            difficulty: 0, // 简单
            tags: ['简单', '已发布'],
            createdTime: new Date().getTime(),
            status: 1, // 状态为在线
          },
          {
            title: '发送到发顺丰单号的副fasdf官回答',
            content: '发射点风格和复旦光华教育体育',
            difficulty: 1, // 中等
            tags: ['困难', '未发布'],
            createdTime: new Date().getTime(),
            status: 0, // 状态为离线
          },
        ];
        renderData.value = mockData; // 将模拟数据赋给renderData
      }, 2000); // 延迟2秒加载
    } catch (error) {
      console.error('Failed to fetch data:', error);
    } finally {
      setLoading(false); // 停止加载
    }
  };
  const colors = [
    'orangered',
    'orange',
    'gold',
    'lime',
    'green',
    'cyan',
    'blue',
    'arcoblue',
    'purple',
    'pinkpurple',
    'magenta',
    'gray',
  ];

  const getTagColor = (index: number) => {
    if (index > colors.length - 1) {
      index %= colors.length;
    }
    return colors[index];
  };

  const changeStatus = (record: any, checked: boolean) => {
    // 在这里添加处理逻辑，例如更新记录状态或发送网络请求等
  };
  const handleOk = async () => {
    if (showStatus.value === 2) {
      try {
        await formTable.value.handleSubmit(); // 等待子组件的验证完成
        showVisible.value = false; // 如果没有错误，关闭modal
      } catch (errors) {
        // 验证失败，modal保持显示
        showVisible.value = true;
      }
    } else {
      showVisible.value = false; // 如果不是编辑状态，直接关闭modal
    }
  };
  const handleCancel = () => {
    showVisible.value = false;
  };
  const view = (record: any) => {
    showVisible.value = true;
    currentRecord.value = record;
    showStatus.value = 1;
  };

  const edit = (record: any) => {
    showVisible.value = true;
    currentRecord.value = record;
    showStatus.value = 2;
  };

  const deleteRecord = async (record: any) => {
    try {
      // await deletePolicy(record.id);
      Message.success('删除成功');
      fetchData();
    } catch (error) {
      Message.error('删除失败');
    }
  };

  const search = async () => {
    fetchData();
  };
  const onSelect = (value: string) => {
    formModel.tag = value;
  };

  const reset = () => {
    // formModel.number = '';
    // formModel.contentType = '';
    // formModel.filterType = '';
    // formModel.filterType = '';
    formModel.status = '';
  };

  const difficultyTypeOptions = [
    { label: '简单', value: 0 },
    { label: '中等', value: 1 },
    { label: '困难', value: 2 },
  ];

  const vipTypeOptions = [
    { label: 'VIP', value: 1 },
    { label: '非VIP', value: 0 },
  ];

  const publishOptions = [
    { label: '已发布', value: 1 },
    { label: '未发布', value: 0 },
  ];

  const onPageChange = (current: number) => {
    // fetchData({ ...basePagination, current });
  };
  onMounted(() => {
    fetchData(); // 组件加载时调用fetchData
  });
</script>

<style scoped></style>
